//
//  dishiViewController.m
//  xinhua_sx
//
//  Created by love on 14-8-7.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//
#define kIOS_VERSION [[UIDevice currentDevice].systemVersion floatValue]
#define DISHI @[@"太原",@"大同",@"阳泉",@"长治",@"晋城",@"朔州",@"晋中",@"运城",@"忻州",@"临汾",@"吕梁"]

#define XIANQU @{\
@"太原" : @[@"小店",@"古交市",@"万柏林",@"晋源"],\
@"大同": @[@"城区",@"蓝郊区",@"浑源",@"灵丘"]            ,\
@"阳泉": @[@"阳泉城区",@"阳泉矿区",@"阳泉郊区",@"盂县"]   ,\
@"长治": @[@"长治郊区",@"襄垣",@"屯留",@"长子"]  ,\
@"晋城": @[@"晋城城区",@"沁水",@"阳城",@"泽州"]        ,\
@"朔州":@[@"朔城区",@"山阴",@"怀仁"]                 ,\
@"晋中": @[@"和顺",@"寿阳",@"平遥",@"灵石"],\
@"运城":@[@"盐湖区",@"永济",@"河津"]                ,\
@"忻州":@[@"忻府区",@"定襄",@"五台",@"代县",@"原平",@"静乐"]  ,\
@"临汾":@[@"尧都区",@"洪洞",@"安泽"]                 ,\
@"吕梁":@[@"离石区",@"柳林",@"交口",@"孝义"]          ,\
}

#import "dishiViewController.h"
#import "AFNetworking.h"
@interface dishiViewController ()
{
    NSUInteger xianquselect;
   // NSUInteger dishiselect;
}
@property (nonatomic, strong) NSMutableArray* buttonArray;
@property (nonatomic, strong) NSMutableArray* allArray;
@end

@implementation dishiViewController
@synthesize selectTage;
@synthesize buttonArray;
@synthesize s1tring;
@synthesize allArray = _allArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _allArray = [[NSMutableArray alloc] init];
        NSUserDefaults* sta = [NSUserDefaults standardUserDefaults];
        _allArray = [sta objectForKey:@"allcode"];
        NSLog(@"_al = %@",_allArray);
    }
    return self;
}

-(void)loaddishi
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
  
    
    NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/areaList-15.html"];
    
    [manager GET:sting parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        NSLog(@"JSON CLASS = %@",[jsonObject class]);
        NSLog(@"json count = %d",[jsonObject count]);
        _allArray = jsonObject;
        for (id item in jsonObject)
        {
            //NSLog(@"item = %@",item);
            NSLog(@"item class = %@",[item class]);
            if ([[item class] isSubclassOfClass:[NSDictionary class]])
            {
                for (id key in item)
                {
                    if ([[key class] isSubclassOfClass:[NSDictionary class]])
                    {
                        for (id key1 in key)
                        {
                             NSLog(@" %@ = %@",key1,key[key1]);
                        }
                    }
                    else
                       NSLog(@"%@ = %@",key,item[key]);
                }
            }
        }
        
        for (int i = 0; i < [jsonObject count]; i ++)
        {
            NSDictionary* item = jsonObject[i];
            NSLog(@"name = %@ id = %@",item[@"name"],item[@"code"]);
            NSArray* xianqu = item[@"childList"];
            
        }
        selectTage = CITYMAINCODE; //复制时替换 可在上面 #define DISHI 里找到 第一个为 10000 依次加1 当前为忻州
        for (int i = 0; i < [_allArray count]; i ++)
        {
            UIButton* button = [[UIButton alloc] init];
            button.frame = CGRectMake(10+55*(i%5), 182+30*(i/5), 50, 25);
            NSDictionary* item = _allArray[i];
            NSLog(@"name = %@ id = %@",item[@"name"],item[@"code"]);
            
            
            [button setTitle:item[@"name"] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:15];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.tag = 10000+i;
            // 设置圆角半径
            button.layer.masksToBounds = YES;
            button.layer.cornerRadius = 2.5;
            //还可设置边框宽度和颜色
            button.layer.borderWidth = 0.15;
            button.layer.borderColor = [UIColor grayColor].CGColor;
            if (selectTage == button.tag)
            {
                [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
            }
            
            //[button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
            //[button setBackgroundColor:[UIColor blueColor]];
            [button addTarget:self action:@selector(dishi:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:button];
            
        }
        xianquselect = -1;
        if ([s1tring isEqualToString:@"只显示地市"])
        {
            return;
        }
        UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(8, 282, 50, 40)];
        l3.backgroundColor = [UIColor clearColor];
        l3.font = [UIFont systemFontOfSize:18];
        l3.text = @"县区";
        [self.view addSubview:l3];
        
        
        [self addxianquButton];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        NSLog(@"error = %@",error);
    }];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat aY = kIOS_VERSION<7.0?0:20;
    UIView* _navBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0+aY)];
    _navBar.backgroundColor = [UIColor colorWithRed:2.0/255 green:102.0/255 blue:172.0/255 alpha:1.0];
    _navBar.userInteractionEnabled = YES;
    
    UILabel* _titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, aY, self.view.frame.size.width, 44)];
    _titleLable.backgroundColor = [UIColor clearColor];
    
    _titleLable.textColor = [UIColor whiteColor];
    _titleLable.font = [UIFont systemFontOfSize:20];
    _titleLable.textAlignment = NSTextAlignmentCenter;
    [_navBar addSubview:_titleLable];
    [self.view addSubview:_navBar];
    buttonArray = [NSMutableArray array];
    UIButton* _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, aY, 40,40.0)];
    //[_leftButton setImage:[UIImage imageNamed:@"icon_back@2x.png"] forState:UIControlStateNormal];
    [_leftButton setTitle:@"取消" forState:UIControlStateNormal];
    _leftButton.imageEdgeInsets = UIEdgeInsetsMake(10, 13, 5, 5);
    [_leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];

    UIButton* _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-40, 5+aY, 40, 40)];
    //[_rightButton setImage:[UIImage imageNamed:@"tab_spinner_normal.png"] forState:UIControlStateNormal];
    [_rightButton setTitle:@"确定" forState:UIControlStateNormal];
    [_rightButton addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_rightButton];
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(8, 66, 50, 40)];
    label.text = @"全国";
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:label];
    UIButton* button = [[UIButton alloc] init];
    button.frame = CGRectMake(10, 100, 50, 25);
    [button setTitle:@"山西" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    // 设置圆角半径
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 2.5;
    //还可设置边框宽度和颜色
    button.layer.borderWidth = 0.15;
    button.layer.borderColor = [UIColor grayColor].CGColor;
    [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
    //[button setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:button];
    
    UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(8, 135, 50, 40)];
    l1.backgroundColor = [UIColor clearColor];
    l1.font = [UIFont systemFontOfSize:18];
    l1.text = @"地市";
    [self.view addSubview:l1];
    if ([_allArray count] == 0)
    {
        [self loaddishi];
        return;


    }

    selectTage = CITYMAINCODE; //复制时替换 可在上面 #define DISHI 里找到 第一个为 10000 依次加1 当前为忻州
    for (int i = 0; i < [_allArray count]; i ++)
    {
        UIButton* button = [[UIButton alloc] init];
        button.frame = CGRectMake(10+55*(i%5), 182+30*(i/5), 50, 25);
        NSDictionary* item = _allArray[i];
        NSLog(@"name = %@ id = %@",item[@"name"],item[@"code"]);
        
        
        [button setTitle:item[@"name"] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.tag = 10000+i;
        // 设置圆角半径
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 2.5;
        //还可设置边框宽度和颜色
        button.layer.borderWidth = 0.15;
        button.layer.borderColor = [UIColor grayColor].CGColor;
        if (selectTage == button.tag)
        {
            [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        }
        
        //[button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        //[button setBackgroundColor:[UIColor blueColor]];
        [button addTarget:self action:@selector(dishi:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        
    }
    xianquselect = -1;
    if ([s1tring isEqualToString:@"只显示地市"])
    {
        return;
    }
    UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(8, 282, 50, 40)];
    l3.backgroundColor = [UIColor clearColor];
    l3.font = [UIFont systemFontOfSize:18];
    l3.text = @"县区";
    [self.view addSubview:l3];
    
    
    [self addxianquButton];
       // Do any additional setup after loading the view.
}

-(void)addxianquButton
{
    
    NSUInteger count =  [_allArray[selectTage-10000][@"childList"] count];
    for (int i = 0; i < count; i ++)
    {
        NSLog(@"i = %d",i);
        UIButton* button = [[UIButton alloc] init];
        button.frame = CGRectMake(10+55*(i%5), 329+30*(i/5), 50, 25);
        NSArray* item =_allArray[selectTage-10000][@"childList"];
        NSDictionary* dic = item[i];
        NSString* title = [dic objectForKey:@"name"];
        [button setTitle:title forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.tag = 20000+i;
        // 设置圆角半径
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 2.5;
       // if (xianquselect == button.tag  )
       // {
       //     [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
       // }
        //还可设置边框宽度和颜色
        button.layer.borderWidth = 0.15;
        button.layer.borderColor = [UIColor grayColor].CGColor;
        //
        //[button setBackgroundColor:[UIColor blueColor]];
        [button addTarget:self action:@selector(xianqu:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [buttonArray addObject:button];
    }

}
-(void)xianqu:(UIButton*)button
{
     if (xianquselect == - 1)
     {
         [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
         xianquselect = button.tag;
         return;
     }
    if (xianquselect != button.tag && xianquselect != -1)
    {
        UIButton* oldbutton = [buttonArray objectAtIndex:xianquselect-20000];
        [oldbutton setBackgroundColor:[UIColor whiteColor]];
        [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        xianquselect = button.tag;
    }
    else if (xianquselect == button.tag)
    {
        UIButton* oldbutton = [buttonArray objectAtIndex:xianquselect-20000];
        [oldbutton setBackgroundColor:[UIColor whiteColor]];
        //[button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        xianquselect = -1;

    }
}
-(void)dishi:(UIButton* )button
{
    
    if (selectTage != button.tag)
    {
        for (id item in buttonArray)
        {
            [item removeFromSuperview];
        }
        [buttonArray removeAllObjects];
        UIButton* oldbutton = (UIButton*)[self.view viewWithTag:selectTage];
        [oldbutton setBackgroundColor:[UIColor whiteColor]];
        [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        selectTage = button.tag;
        if ([s1tring isEqualToString:@"只显示地市"])
        {
            return;
        }//file:///Users/love/Desktop/xinhua2.0/xinhua_sx/Home/base_detail_default_pic.png
        //xianquselect = 20000;
        [self addxianquButton];
    }
    else
    {
        [button setBackgroundColor:[dishiViewController colorWithHexString:@"#A6C4E8"]];
        selectTage = button.tag;

    }
    //NSLog(@"buttonArray = %@",buttonArray);
}
-(void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

-(void)rightClick
{
    if (self.block)
    {
        NSString* str;
        NSString* ff;
        if ([s1tring isEqualToString:@"只显示地市"])
        {
            NSDictionary* item = _allArray[selectTage-10000];
            str  = item[@"name"];
            ff = item[@"code"];
            NSLog(@"%@= %@",str,ff);
            
            
            
            //ff = [DISHI objectAtIndex:selectTage-10000];
            // str = [self getAREACODe:ff];
        }
        else
        {
            if (xianquselect == -1) // 用户没有选择县区
            {
                NSDictionary* item = _allArray[selectTage-10000];
                str  = item[@"name"];
                ff = item[@"code"];
                NSLog(@"%@= %@",str,ff);
              // 、、 ff = [DISHI objectAtIndex:selectTage-10000];
        ///、、//、、str = [self getAREACODe:ff];
                
            }
            else
            {
                NSDictionary* item = _allArray[selectTage-10000][@"childList"][xianquselect-20000];
                str  = item[@"name"];
                ff = item[@"code"];
                NSLog(@"%@= %@",str,ff);
                
              //   ff  = [[XIANQU objectForKey:[DISHI objectAtIndex:selectTage-10000]] objectAtIndex:xianquselect-20000];
             //   str = [self getAREACODe:ff];
                
            }
            
            

        }
        self.block(str,ff);
        [self dismissViewControllerAnimated:YES completion:nil];
        
      
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSString*)getAREACODe:(NSString*)address
{
    if([@"太原" isEqualToString:address]){
        return @"140100";
    }
    if([@"大同" isEqualToString:address]){
        return @"037000";
    }
    if([@"阳泉" isEqualToString:address]){
        return @"045000";
    }
    if([@"长治" isEqualToString:address]){
        return @"046001";
    }
    if([@"晋城" isEqualToString:address]){
        return @"048000";
    }
    if([@"朔州" isEqualToString:address]){
        return @"036001";
    }
    if([@"晋中" isEqualToString:address]){
        return @"140700";
    }
    if([@"运城" isEqualToString:address]){
        return @"044000";
    }
    if([@"忻州" isEqualToString:address]){
        return @"034000";
    }
    if([@"临汾" isEqualToString:address]){
        return @"041000";
    }
    if([@"吕梁" isEqualToString:address]){
        return @"033000";
    }
    if([@"小店" isEqualToString:address]){
        return @"140105";
    }
    if([@"古交市" isEqualToString:address]){
        return @"030200";
    }
    if([@"万柏林" isEqualToString:address]){
        return @"030021";
    }
    if([@"晋源" isEqualToString:address]){
        return @"140110";
    }
    if([@"城区" isEqualToString:address]){
        return @"037001";
    }
    if([@"南郊区" isEqualToString:address]){
        return @"037002";
    }
    if([@"浑源" isEqualToString:address]){
        return @"037400";
    }
    if([@"灵丘" isEqualToString:address]){
        return @"034400";
    }
    if([@"阳泉城区" isEqualToString:address]){
        return @"045002";
    }
    if([@"阳泉矿区" isEqualToString:address]){
        return @"045003";
    }
    if([@"阳泉郊区" isEqualToString:address]){
        return @"045001";
    }
    if([@"盂县" isEqualToString:address]){
        return @"045100";
    }
    if([@"长治郊区" isEqualToString:address]){
        return @"046002";
    }
    if([@"襄垣" isEqualToString:address]){
        return @"046200";
    }
    if([@"屯留" isEqualToString:address]){
        return @"046100";
    }
    if([@"长子" isEqualToString:address]){
        return @"046600";
    }
    if([@"晋城城区" isEqualToString:address]){
        return @"048002";
    }
    if([@"沁水" isEqualToString:address]){
        return @"048200";
    }
    if([@"阳城" isEqualToString:address]){
        return @"048100";
    }
    if([@"泽州" isEqualToString:address]){
        return @"048001";
    }
    if([@"朔城区" isEqualToString:address]){
        return @"036002";
    }
    if([@"山阴" isEqualToString:address]){
        return @"036900";
    }
    if([@"怀仁" isEqualToString:address]){
        return @"038300";
    }
    if([@"和顺" isEqualToString:address]){
        return @"032700";
    }
    if([@"寿阳" isEqualToString:address]){
        return @"140725";
    }
    if([@"平遥" isEqualToString:address]){
        return @"031100";
    }
    if([@"灵石" isEqualToString:address]){
        return @"031301";
    }
    if([@"盐湖区" isEqualToString:address]){
        return @"044001";
    }
    if([@"永济" isEqualToString:address]){
        return @"044500";
    }
    if([@"河津" isEqualToString:address]){
        return @"043300";
    }
    if([@"忻府区" isEqualToString:address]){
        return @"034001";
    }
    if([@"定襄" isEqualToString:address]){
        return @"335400";
    }
    if([@"五台" isEqualToString:address]){
        return @"335500";
    }
    if([@"代县" isEqualToString:address]){
        return @"034200";
    }
    if([@"原平" isEqualToString:address]){
        return @"034100";
    }
    if([@"尧都区" isEqualToString:address]){
        return @"041002";
    }
    if([@"洪洞" isEqualToString:address]){
        return @"031600";
    }
    if([@"安泽" isEqualToString:address]){
        return @"042500";
    }
    if([@"离石区" isEqualToString:address]){
        return @"033099";
    }
    if([@"柳林" isEqualToString:address]){
        return @"033300";
    }
    if([@"交口" isEqualToString:address]){
        return @"032499";
    }
    if([@"孝义" isEqualToString:address]){
        return @"032300";
    }
    if([@"静乐" isEqualToString:address]){
        return @"035100";
    }
    return COUTURYCODE;//复制时替换成 县区code
    
}

@end
